package com.crdeng.system.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crdeng.system.entity.User;
import com.crdeng.system.mapper.UserMapper;
import com.crdeng.system.service.UserService;
import com.crdeng.system.vo.Permission;
import com.crdeng.system.vo.UserRoleVO;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.rmi.runtime.Log;

import javax.sound.midi.Soundbank;
import java.util.HashSet;
import java.util.List;

@Service
public class MemberDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      /*  QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.eq("username",username);
        User user = userService.getOne(userQueryWrapper);
*/
      UserRoleVO userRoleVO = userService.findByUsername(username);
      if (userRoleVO==null){
          return null;
      }
        List<Permission> list = userService.getGrantedAuthority(userRoleVO.getUsername());
        HashSet<GrantedAuthority> grantedAuthorities = new HashSet<>();
        list.forEach((user)->{
            //如果权限为空则不加入
            if (!StringUtils.isEmpty(user.getPerms())) {
                grantedAuthorities.add(new SimpleGrantedAuthority(user.getPerms()));}
        });
        userRoleVO.setAuthorities(grantedAuthorities);

        return userRoleVO;
    }
}
